package com.jdk.demo.fileChannel.batchRead;

import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class Test4_3 {

	private static FileInputStream fisRef;
	private static FileChannel fileChannel;
	
	// 验证read方法具有同步性
	// 注意，一定要在d1文件的最后一行加上\r\n
	public static void main(String[] args) throws Exception {
		fisRef = new FileInputStream(new File("d1.txt"));
		fileChannel = fisRef.getChannel();
		
		for (int i = 0; i < 10; i++) {
			Thread thread1 = new Thread(){
				@Override
				public void run(){
					try{
						ByteBuffer buffer1 = ByteBuffer.allocate(8);
						ByteBuffer buffer2 = ByteBuffer.allocate(8);
						ByteBuffer[] bufferArray = new ByteBuffer[]{buffer1, buffer2};
						long readLength = fileChannel.read(bufferArray);
						while(readLength != -1){
							// 同步的目的是输出的有序性
							synchronized (Test4_3.class) {
								for (int j = 0; j < bufferArray.length; j++) {
									byte[] getByte = bufferArray[j].array();
									for (int k = 0; k < getByte.length; k++) {
										System.out.print((char)getByte[k]);
									}
								}
							}
							buffer1.clear();
							buffer2.clear();
							readLength = fileChannel.read(bufferArray);
						}
					}catch(Exception e){
						e.printStackTrace();
					}
				}
			};
			Thread thread2 = new Thread(){
				@Override
				public void run(){
					try{
						ByteBuffer buffer1 = ByteBuffer.allocate(8);
						ByteBuffer buffer2 = ByteBuffer.allocate(8);
						ByteBuffer[] bufferArray = new ByteBuffer[]{buffer1, buffer2};
						long readLength = fileChannel.read(bufferArray);
						while(readLength != -1){
							// 同步的目的是输出的有序性
							synchronized (Test4_3.class) {
								for (int j = 0; j < bufferArray.length; j++) {
									byte[] getByte = bufferArray[j].array();
									for (int k = 0; k < getByte.length; k++) {
										System.out.print((char)getByte[k]);
									}
								}
							}
							buffer1.clear();
							buffer2.clear();
							readLength = fileChannel.read(bufferArray);
						}
					}catch(Exception e){
						e.printStackTrace();
					}
				}
			};
			thread1.start();
			thread2.start();
		}
		
		// 经过分析，一共输出了40个字符串，ooooo1和ooooo2为一组，一共10组；zzzzz1和zzzzz2为一组，一共10组。说明了read方法同步性
		Thread.sleep(3000);
		fileChannel.close();
		fisRef.close();
	}
	
}
